package com.hwj.controller;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.github.pagehelper.PageInfo;
import com.hwj.entity.Post;
import com.hwj.entity.User;
import com.hwj.service.PostService;
import com.hwj.service.UserInfoService;
import com.hwj.utils.JsonResponse;
import javafx.geometry.Pos;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
@RequestMapping("/post")
@Slf4j
public class PostController {

    @Autowired
    PostService postService;
    @Autowired
    UserInfoService userInfoService;

    /*用户端主页分页*/
    @PostMapping("/page")
    public JsonResponse page(@RequestBody(required = false) Post post, @RequestParam(value = "postTypeName", required = false) String postTypeName, @RequestParam(value = "pageNum", required = false) Integer pageNum, @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        return JsonResponse.successResponse(0, "分页查询帖子信息成功", postService.page(post, postTypeName, pageNum, pageSize));
    }

    /*管理端帖子管理分页*/
    @PostMapping("/pageManger")
    public JsonResponse pageManger(@RequestBody(required = false) Post post, @RequestParam(value = "pageNum", required = false) Integer pageNum, @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        PageInfo<Post> page = postService.pageManage(post, pageNum, pageSize);
        return JsonResponse.successResponse(0, "分页查询帖子信息成功", page);
    }

    /*管理端帖子审核分页*/
    @PostMapping("/pageExam")
    public JsonResponse pageExam(@RequestBody(required = false) Post post, @RequestParam(value = "pageNum", required = false) Integer pageNum, @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        PageInfo<Post> page = postService.pageExam(post, pageNum, pageSize);
        return JsonResponse.successResponse(0, "分页查询帖子信息成功", page);
    }

    /*前台浏览数排行榜*/
    @GetMapping("/selectViews")
    public JsonResponse selectViews() {
        return JsonResponse.successResponse(0, "查询浏览数帖子信息成功", postService.selectView());
    }

    /*前台收藏数排行榜*/
    @GetMapping("/selectFavorites")
    public JsonResponse selectFavorites() {
        return JsonResponse.successResponse(0, "查询收藏数帖子信息成功", postService.selectFavorites());
    }

    /*前台喜欢数排行榜*/
    @GetMapping("/selectLikes")
    public JsonResponse selectLikes() {
        return JsonResponse.successResponse(0, "查询点赞数帖子信息成功", postService.selectLikes());
    }

    /*前台用于详情页请别乱用*/
    @GetMapping("/selectById/{postId}")
    public JsonResponse selectById(@PathVariable Long postId) {
        Post post = postService.selectByPrimaryKey(postId);

        //该帖子主人信息
        User user = userInfoService.queryById(post.getUserId());
        post.setUser(user);

        //该用户下帖子数，点赞数，收藏数
        List<Post> posts = postService.selectByUserIdPosts(post.getUserId());
        Long postCount=0l;
        Long postFavoriteCount=0l;
        Long postLikeCount=0l;
        for(Post post1:posts){
            postCount++;
            postLikeCount+=post1.getLikes();
            postFavoriteCount+=post1.getFavorites();
        }
        post.setPostCount(postCount);
        post.setPostLikeCount(postLikeCount);
        post.setPostFavoriteCount(postFavoriteCount);
        return JsonResponse.successResponse(0, "查询单个帖子信息成功", post);
    }

    /*前台后台新增或更新帖子*/
    @PutMapping("/")
    public JsonResponse update(@RequestBody Post post) {
        if (post.getPostId() == null) {
            int i = postService.insertSelective(post);
            if (i == 1) {
                return JsonResponse.successResponse(0, "新增帖子信息成功", null);
            } else {
                return JsonResponse.failResponse(-2, "新增帖子信息失败", null);
            }
        } else {
            int i = postService.updateByPrimaryKey(post);
            if (i == 1) {
                return JsonResponse.successResponse(0, "更新帖子信息成功", null);
            }
            return JsonResponse.failResponse(-2, "更新用户帖子失败", null);
        }
    }

    /*前台后台删除帖子信息（逻辑删除）*/
    @DeleteMapping("/{postId}")
    public JsonResponse delete(@PathVariable Long postId){
        return JsonResponse.successResponse(0, "删除单个帖子信息成功", postService.deleteByPrimaryKey(postId));
    }

    /**
     * 永久删除
     * @param postId
     * @return
     */
    @DeleteMapping("/delete/{postId}")
    public JsonResponse deleteForever(@PathVariable Long postId){
        return JsonResponse.successResponse(0, "删除单个帖子信息成功", postService.deleteForever(postId));
    }

    /*前台标签的相关推荐*/
    @GetMapping("/selectRecommend/{postId}")
    public JsonResponse selectRecommend(@PathVariable Long postId){
        Set set = postService.selectRecommend(postId);
        return JsonResponse.successResponse(0,"查询相关推荐成功",set);
    }

    /*前台浏览数增加*/
    @PostMapping("/updateViews")
    public JsonResponse updateViews(@RequestBody Post post1){
        Post post = postService.selectByPrimaryKey(post1.getPostId());
        Long count=post.getViews();
        count++;
        post.setViews(count);
        postService.updateByPrimaryKey(post);
        return JsonResponse.successResponse(0,"帖子浏览自增成功",null);
    }

    /*前台查看用户的收藏*/
    @PostMapping("/myStarPost")
    public JsonResponse myStarPost(HttpServletRequest request){
        JWT jwt = JWTUtil.parseToken(request.getHeader("token"));
        Object userId = jwt.getPayload("userId");
        return JsonResponse.successResponse(0,"查询当前登陆用户收藏的帖子成功",postService.myStarPost(Long.parseLong(userId+"")));
    }

    /*前台查看用户的收藏*/
    @PostMapping("/myLikePost")
    public JsonResponse myLikePost(HttpServletRequest request){
        JWT jwt = JWTUtil.parseToken(request.getHeader("token"));
        Object userId = jwt.getPayload("userId");
        return JsonResponse.successResponse(0,"查询当前登陆用户收藏的帖子成功",postService.myLikePost(Long.parseLong(userId+"")));
    }

    /*前台查看用户的收藏*/
    @PostMapping("/myPost")
    public JsonResponse myPost(HttpServletRequest request){
        JWT jwt = JWTUtil.parseToken(request.getHeader("token"));
        Object userId = jwt.getPayload("userId");
        return JsonResponse.successResponse(0,"查询当前登陆用户收藏的帖子成功",postService.myPost(Long.parseLong(userId+"")));
    }

    /*前台查看用户待审核的帖子*/
    @PostMapping("/myExamPost")
    public JsonResponse myExamPost(HttpServletRequest request){
        JWT jwt = JWTUtil.parseToken(request.getHeader("token"));
        Object userId = jwt.getPayload("userId");
        return JsonResponse.successResponse(0,"查询当前登陆用户收藏的帖子成功",postService.myExamPost(Long.parseLong(userId+"")));
    }
    /*前台查看已发布的帖子信息*/
    @PostMapping("/myPublishPost")
    public JsonResponse myPublishPost(HttpServletRequest request){
        JWT jwt = JWTUtil.parseToken(request.getHeader("token"));
        Object userId = jwt.getPayload("userId");
        return JsonResponse.successResponse(0,"查询当前登陆用户收藏的帖子成功",postService.myPublishPost(Long.parseLong(userId+"")));
    }

    /*前台查看已下架的帖子信息*/
    @PostMapping("/under")
    public JsonResponse underPost(HttpServletRequest request){
        JWT jwt = JWTUtil.parseToken(request.getHeader("token"));
        Object userId = jwt.getPayload("userId");
        return JsonResponse.successResponse(0,"查询当前登陆用户下架的帖子成功",postService.underPost(Long.parseLong(userId+"")));
    }

    /*前台热榜*/
    @PostMapping("/pageHot")
    public JsonResponse pageHot(Integer pageNum,Integer pageSize) {
        List<Post> list = postService.listAll();
        List<Post> page =list.stream().skip((pageNum-1)*pageSize)
                .limit(pageSize).collect(Collectors.toList());
        PageInfo<Post> pageInfo=new PageInfo<>(page);
        pageInfo.setPageNum(pageNum);
        pageInfo.setPageSize(pageSize);
        pageInfo.setTotal(list.size());
        return JsonResponse.successResponse(0, "分页查询帖子信息成功", pageInfo);
    }

    /*前台搜索框*/
    @PostMapping("/search")
    public JsonResponse search(String title,Integer pageSize,Integer pageNum,HttpServletRequest request){
        JWT jwt = JWTUtil.parseToken(request.getHeader("token"));
        Long userId = Long.parseLong(jwt.getPayload("userId")+"");
        return JsonResponse.successResponse(0, "查询帖子信息成功", postService.search(title,pageNum,pageSize,userId));
    }
    /*前台标签*/
    @PostMapping("/tag")
    public JsonResponse tag(String tag,Integer pageSize,Integer pageNum){
        return JsonResponse.successResponse(0, "查询帖子信息成功", postService.tag(tag,pageNum,pageSize));
    }
}
